<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
        <el-button v-permission="'coupon:config:create'" icon="circle-plus" plain type="primary" @click="handleFormShow(1, 0)">新增</el-button>
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">

            <template #amount="scope">
              <span>{{ numeral(scope.row.amount).format('0.00') }}元</span>
            </template>

            <template #status="scope">
              <DictTag v-model="scope.row.status" :circle="false" dict-type="coupon_status"/>
            </template>

            <template #valid_type="scope">
              <DictTag v-model="scope.row.valid_type" :circle="false" dict-type="coupon_valid_type"/>
            </template>

            <template #deleted="scope">
              <DictTag v-model="scope.row.deleted" :circle="false" dict-type="sys_deleted"/>
            </template>

            <template #valid_time="scope">
              <span v-if="scope.row.valid_type === 0">-</span>
              <span v-else-if="scope.row.valid_type === 1">{{ dayjs(scope.row.valid_time_from * 1000).format('YYYY-MM-DD HH:mm') }} ~ {{ dayjs(scope.row.valid_time_to * 1000).format('YYYY-MM-DD HH:mm') }}</span>
              <span v-else-if="scope.row.valid_type === 2">{{ scope.row.valid_fixed_days }}天</span>
            </template>

            <template #operations="scope">
              <el-button v-permission="'coupon:config:info'" link type="info" @click="handleFormShow(0, scope.row.id)">查看</el-button>
              <el-button v-permission="'coupon:config:update'" link type="primary" @click="handleFormShow(2, scope.row.id)">编辑</el-button>
              <template v-if="!scope.row.deleted">
                <el-button v-permission="'coupon:config:give_away'" link type="warning" @click="handleGiveAwayFormFormShow(scope.row)">赠送</el-button>
                <el-button v-permission="'coupon:config:delete'" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 弹窗操作 -->
    <ConfigForm ref="formRef" @refresh="handleSearch"/>
    <!-- 消费券赠送 -->
    <CouponGiveAwayForm ref="giveAwayFormRef" @refresh="handleSearch"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import { ElLoading, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { hasPermission } from '@/utils/permission.ts';
import { computedOperateWidth } from '@/utils';
import { DictTag } from '@/components/dict-tag';
import ConfigForm from './form.vue';
import CouponGiveAwayForm from './give-away-form.vue';
import useTableSelection from '@/hooks/use-table-selection.ts';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { QueryForm } from '@/components/query-form';
import { couponDelete, couponList } from '@/api/api-coupon.ts';
import numeral from 'numeral';
import dayjs from 'dayjs';

defineOptions({name: 'coupon-list'});

// 查询
const queryFormData = reactive({
  title: undefined,
  valid_type: undefined,
  status: undefined,
  deleted: 0,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'name', label: '名称', placeholder: '请输入名称', clearable: true,},
  {type: 'dict-select', prop: 'status', label: '状态', placeholder: '请选择', dictType: 'coupon_status', clearable: true,},
  {type: 'dict-select', prop: 'valid_type', label: '使用限制', placeholder: '请选择使用限制', dictType: 'coupon_valid_type', clearable: true,},
  {type: 'dict-select', prop: 'deleted', label: '是否删除', placeholder: '请选择是否删除', dictType: 'sys_deleted', clearable: true,},
]);

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('coupon:config:info')) count += 1
  if (hasPermission('coupon:config:update')) count += 1
  if (hasPermission('coupon:config:delete')) count += 1
  if (hasPermission('coupon:config:give_away')) count += 1
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'id', label: '编号', width: 105, align: 'center', sortable: 'custom'},
  {prop: 'status', label: '状态', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'title', label: '名称', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'amount', label: '面值', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'valid_type', label: '使用限制', minWidth: 115, align: 'center', sortable: 'custom'},
  {prop: 'valid_time', label: '使用时间', minWidth: 280, align: 'center'},
  {prop: 'issued_count', label: '发布数量', minWidth: 130, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'deleted', label: '是否删除', minWidth: 110, align: 'center', sortable: 'custom'},
  {prop: 'create_time', label: '创建时间', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'update_time', label: '更新时间', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 查询数据
    const {data} = await couponList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  clearSelection();
  handleResetForm();
};

/** 添加/修改操作 */
const formRef = ref<any>()
const handleFormShow = (mode: number, id?: number) => {
  formRef.value?.open(mode, id)
};

/** 消费券赠送 */
const giveAwayFormRef = ref<any>()
const handleGiveAwayFormFormShow = (row: any) => {
  giveAwayFormRef.value?.open(row)
};

/** 删除操作 */
const handleDelete = (row: any) => {
  ElMessageBox({
    title: '操作确认',
    message: h('p', null, ['是否确认删除 ', h('span', {style: 'font-weight: bold'}, row.title), ' 的消费券吗？', <br/>, '删除后将无法恢复，请谨慎操作！']),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
  }).then((action) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在处理中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    couponDelete(row.id).then(() => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};
</script>

<style lang="scss" scoped>

</style>
